#!/bin/bash

# deepin 15 到 20 的升级脚本。
# 双击，选择在终端中执行。或者在脚本所在目录打开终端，执行 ./upgrade15to20.sh

get_char()
{
    SAVEDSTTY=`stty -g`
    stty -echo
    stty cbreak
    dd if=/dev/tty bs=1 count=1 2> /dev/null
    stty -raw
    stty echo
    stty $SAVEDSTTY
}

add_source_update()
{
    echo "安装必要的组件..."

    sudo apt update
    sudo apt install dirmngr -y

    echo -e "\n"

    echo "添加 deepin v20 官方源..."

    echo -e "\n"

    echo "/etc/apt/sources.list："

    sudo tee /etc/apt/sources.list <<< "deb [by-hash=force] https://community-packages.deepin.com/deepin/ apricot main contrib non-free"
    
    if [[ $? -ne 0 ]]; then
        echo "添加官方源失败。"
        return 1
    fi

    echo -e "\n"

    echo "/etc/apt/sources.list.d/appstore.list："
    
    sudo tee /etc/apt/sources.list.d/appstore.list <<< "deb https://community-store-packages.deepin.com/appstore eagle appstore"
    
    if [[ $? -ne 0 ]]; then
        echo "添加官方商店源失败。" 
        return 1
    fi

    sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 1C30362C0A53D5BB

    if [[ $? -ne 0 ]]; then
        echo "添加官方商店源公钥失败。" 
        return 1
    fi

    echo -e "\n"
    
    read -p "是否立即检查并更新系统？（Y/N）[默认=N]" choice
    
    case $choice in
      y|Y ) ;;
      * ) 
        echo "请自行检查更新。"
        return 0
        ;;
    esac

    echo -e "\n"
    
    sudo apt update
    
    if [[ $? -ne 0 ]]; then
        echo "检查更新失败。"
        return 1
    fi

    echo -e "\n"

    echo "即将开始更新系统，此操作不可逆转。更新过程中可能会有一些选项需要用户选择，如果有不确定的地方，请尽量搞清楚再操作。"
    read -p "是否继续？（Y/N）[默认=N]" choice
    
    case $choice in
      y|Y ) ;;
      * ) 
        echo "请自行更新系统。"
        return 0
        ;;
    esac

    echo -e "\n"

    echo "开始更新系统..."  
    
    sudo apt dist-upgrade -y

    # 稳妥点，出错了就再执行一次
    if [[ $? -ne 0 ]]; then
        sudo -S apt dist-upgrade -y

        if [[ $? -ne 0 ]]; then
            echo "更新系统失败。"
            return 0
        fi
    fi
    
    return 0
}

############################################

if [[ $(sudo -S whoami) != "root" ]]; then
    echo "请以管理员身份运行此脚本..."
    #get_char
    exit 1
fi

echo "此程序为方便新手将 deepin 15.11 升级为 deepin 20 所做，实际操作中出现任何问题，此程序概不负责。"
read -p "是否继续？（Y/N）[默认=N]" choice

case $choice in
  y|Y ) ;;
  * ) exit 0;;
esac

echo -e "\n"

echo "备份 /etc/apt/sources.list"

sudo cp -f /etc/apt/sources.list /etc/apt/sources.list.bak

if [[ $? -ne 0 ]]; then
    echo "备份 /etc/apt/sources.list 失败。"
    exit 1
fi

echo -e "\n"

add_source_update

if [[ $? -ne 0 ]]; then
    read -p "是否需要还原 /etc/apt/sources.list？（Y/N）[默认=N]" choice

    case $choice in
      y|Y )
        echo "还原 /etc/apt/sources.list"

        sudo mv -f /etc/apt/sources.list.bak /etc/apt/sources.list

        if [[ $? -ne 0 ]]; then
            sudo -S mv -f /etc/apt/sources.list.bak /etc/apt/sources.list
        fi

        exit 1
        ;;
      * ) ;;
    esac
fi

echo "清理不再使用的软件包..."

sudo apt autopurge -y

if [[ $? -ne 0 ]]; then
    sudo -S apt autopurge -y
fi

sudo apt clean

